package reg

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"go2/http"
	"go2/log"
	"net/url"
	"time"
)

type Links struct {
	Self string `json:"self"`
	HTML string `json:"html"`
}

type Response1 struct {
	Type        string `json:"type"`
	Encoding    string `json:"encoding"`
	Size        int    `json:"size"`
	Name        string `json:"name"`
	Path        string `json:"path"`
	Content     string `json:"content"`
	Sha         string `json:"sha"`
	URL         string `json:"url"`
	HTMLURL     string `json:"html_url"`
	DownloadURL string `json:"download_url"`
	Links       Links  `json:"_links"`
}

type Response2 struct {
	Sha      string `json:"sha"`
	Size     int    `json:"size"`
	URL      string `json:"url"`
	Content  string `json:"content"`
	Encoding string `json:"encoding"`
}

type RecvJsonStruct struct {
	Online string `json:"online"`
	Msg    string `json:"msg"`
}

const (
	URL = "https://gitee.com/api/v5/repos"
)

func GetGiteeFileContent(owner, repo, ref, filename, token string) []byte {
	log.Debug("获取密钥 ...")
	var temp1 Response1
	http.Client().Get(fmt.Sprintf("%s/%s/%s/contents/%s?access_token=%s&ref=%s", URL, owner, repo, filename, token, ref)).SetSuccessResult(&temp1).Do()

	log.Debug("获取文件内容 ...")
	var temp2 Response2
	http.Client().Get(fmt.Sprintf("%s/%s/%s/git/blobs/%s?access_token=%s", URL, owner, repo, temp1.Sha, token)).SetSuccessResult(&temp2).Do()

	var temp []byte
	if temp2.Encoding == "base64" {
		log.Debug("转码文件数据 ...")
		temp, _ = base64.StdEncoding.DecodeString(temp2.Content)
	} else {
		temp = []byte(temp2.Content)
	}

	return temp
}

func regist2(owner, repo, ref, filename, token string) bool {
	temp := GetGiteeFileContent(owner, repo, ref, filename, token)

	log.Debug("解析授权数据 ...")
	var RecvJSON RecvJsonStruct
	json.Unmarshal(temp, &RecvJSON)

	log.Debug(RecvJSON.Msg)

	return RecvJSON.Online == "yes"
}

func Regist(owner, repo, ref, filename, token string, check_time time.Duration) bool {
	filename_url := url.QueryEscape(filename)

	if !regist2(owner, repo, ref, filename_url, token) {
		log.Debug("获取授权失败")
		return false
	}

	return true
}
